package com.ruge.activiti;


import com.ruge.act.ActivitiHistoryQuery;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.activiti.engine.HistoryService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

@SpringBootTest
public class RugeActivitiTask {

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;

    @Resource
    private HistoryService historyService;

    @Test
    public void allTask() {
        //删除流程定义
        System.out.println("清理历史数据 start");
        repositoryService.createProcessDefinitionQuery().list().forEach(processDefinition -> {
            repositoryService.deleteDeployment(processDefinition.getDeploymentId(), true);
        });
        System.out.println("清理历史数据 end");
        //流程部署
        System.out.println("流程部署 start");
        Deployment deploy = repositoryService.createDeployment()
                .addClasspathResource("activiti/processes/jiaban_tasklistener.bpmn20.xml")
                .name("加班申请流程001")
                .category("业务分类，可自行定义")
                .deploy();
        System.out.println("deploy.getId():" + deploy.getId());
        System.out.println("deploy.getName():" + deploy.getName());
        System.out.println("deploy.getCategory():" + deploy.getCategory());
        System.out.println("流程部署 end");


        System.out.println("流程发起 start");
        // 常规 人员ID
        String businessKey = "009";
        // 启动流程实例，指定业务标识businessKey，也就是请假申请单id
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("jiaban_tasklistener", businessKey);
        // 输出
        System.out.println("processInstance.getProcessInstanceId()：" + processInstance.getProcessInstanceId());
        System.out.println("processInstance.getProcessDefinitionId()：" + processInstance.getProcessDefinitionId());
        System.out.println("processInstance.getId()：" + processInstance.getId());
        System.out.println("processInstance.getActivityId():" + processInstance.getActivityId());
        System.out.println("processInstance.getBusinessKey():" + processInstance.getBusinessKey());
        System.out.println("流程发起 end");


        System.out.println("获取审批人信息 start");
        // 所有候选人
        List<String> allUser = new ArrayList<>();
        // 查询当前任务
        List<Task> tasks = taskService.createTaskQuery()
                .processInstanceId(processInstance.getProcessInstanceId())
                .list();
        for (Task task : tasks) {
            // 获取任务的审批人
            String assignee = task.getAssignee();
            if (assignee != null) {
                System.out.println("任务ID: " + task.getId() + ", 审批人: " + assignee);
            }

            // 获取任务的候选组和候选用户
            List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(task.getId());
            List<String> candidateGroups = new ArrayList<>();
            List<String> candidateUsers = new ArrayList<>();
            for (IdentityLink link : identityLinks) {
                if ("candidate".equals(link.getType())) {
                    if (link.getGroupId() != null) {
                        candidateGroups.add(link.getGroupId());
                    }
                    if (link.getUserId() != null) {
                        candidateUsers.add(link.getUserId());
                    }
                }
            }
            System.out.println("任务ID: " + task.getId() + ", 候选组: " + candidateGroups);
            System.out.println("任务ID: " + task.getId() + ", 候选用户: " + candidateUsers);
            allUser.addAll(candidateGroups);
            allUser.addAll(candidateUsers);
            // 随机选择一个候选人并分配任务
            if (!candidateUsers.isEmpty()) {
                int randomIndex = new Random().nextInt(candidateUsers.size());
                String selectedUser = candidateUsers.get(randomIndex);
                taskService.claim(task.getId(), selectedUser);
                System.out.println("任务ID: " + task.getId() + " 已分配给随机选择的用户: " + selectedUser);
                // 完成任务
                taskService.complete(task.getId());
                System.out.println("任务ID: " + task.getId() + " 已完成 ");
            }


        }
        System.out.println("获取审批人信息 end");

        // 查询个人任务代办
        System.out.println("查询个人任务代办 start");
        allUser.forEach(e -> {
            List<Task> list = taskService.createTaskQuery()
                    .taskAssignee(e)
                    .list();
            list.forEach(task -> {
                System.out.println("任务ID: " + task.getId() + ", 审批人: " + task.getAssignee() + ",任务名称:" + task.getName());
            });
        });
        System.out.println("查询个人任务代办 end");

        // 查询所有节点的审批人信息
        System.out.println("查询所有节点的审批人信息 start");
        List<org.activiti.engine.history.HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstance.getProcessInstanceId())
                .list();
        for (org.activiti.engine.history.HistoricTaskInstance historicTask : historicTaskInstances) {
            String assignee = historicTask.getAssignee();
            if (assignee != null) {
                System.out.println("任务名称: " + historicTask.getName() + ", 任务ID: " + historicTask.getId() + ", 审批人: " + assignee);
            } else {
                System.out.println("任务名称: " + historicTask.getName() + ", 任务ID: " + historicTask.getId() + ", 审批人: 无");
            }
        }
        System.out.println("查询所有节点的审批人信息 end");
    }
}
